package pe.com.cineplanet.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver;

import pe.com.cineplanet.bean.User;
import pe.com.cineplanet.bean.cineplanet.Carrito;
import pe.com.cineplanet.bean.cineplanet.CarritoDetalle;
import pe.com.cineplanet.bean.cineplanet.Producto;
import pe.com.cineplanet.bean.cineplanet.UsuarioWeb;
import pe.com.cineplanet.cons.Const;
import pe.com.cineplanet.dao.dao.CarritoDAO;
import pe.com.cineplanet.form.CarritoComprasForm;

public class CarritoComprasController extends MultiActionController {

	private CarritoComprasForm form;
	private CarritoDAO carritoDAO;
	private Class<?> commandClass;  
	
	public void setCarritoDAO(CarritoDAO carritoDAO) {
		this.carritoDAO = carritoDAO;
	}
	
	public CarritoComprasController()
    {
        ParameterMethodNameResolver resolver = new ParameterMethodNameResolver();
        resolver.setParamName("method");
        resolver.setDefaultMethodName("view");
        setMethodNameResolver(resolver);
    }
	
	
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response)
    throws Exception {
		return new ModelAndView("carrito/producto");
    } 

	public ModelAndView carrito(HttpServletRequest request, HttpServletResponse response)
    throws Exception {
		ModelAndView view = new ModelAndView("carrito/carrito");

		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Const.SESSION_KEY);
		
		if(user!=null){
			UsuarioWeb usuario = new UsuarioWeb(user.getLogin());
			Carrito carrito = carritoDAO.existCarrito(usuario);
			if(carrito!=null){
				List<CarritoDetalle> detalle = carritoDAO.detailFrom(carrito);
				view.addObject("carrito", carrito);
				view.addObject("detalleList", detalle);
			}else{
				
				view.addObject("mensaje", "No se ha escogido ningun producto.");
				
			}
		}else{
			view.addObject("mensaje", "Para ver el carrito de compras se debe loguear primero.");
		}
		
		
		
		return view;
		
    } 
	
	public ModelAndView buscar(HttpServletRequest request, HttpServletResponse response)
    throws Exception {
		ModelAndView view = new ModelAndView("carrito/buscar");

		getForm(request);
		
		String searchValue = form.getSearchValue();
		List<Producto> productoList = carritoDAO.findProductoByDesc(searchValue);
	
		view.addObject("productoList", productoList);
		
		return view;
		
    }
	
	
	public ModelAndView agregar(HttpServletRequest request, HttpServletResponse response)
    throws Exception {

		System.out.println("------------------------- Agregar producto a carrito");
		
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Const.SESSION_KEY);
		
		JSONObject root = new JSONObject();

		if(user==null){
			root.put("msg", "login");	
		}else{
			
			UsuarioWeb usuario = new UsuarioWeb(user.getLogin());
			
			getForm(request);

			Carrito carrito = carritoDAO.existCarrito(usuario);
			System.out.println("exuste carrito? ");
			if(carrito==null){
				System.out.println("se creo carrito");
				carrito = carritoDAO.crearCarrito(usuario);
			}
			
			Producto producto = carritoDAO.findProductoById(new Integer(form.getProductoId()));
			System.out.println("Producto : " + producto);
			carritoDAO.agregarProducto(producto, carrito, form.getCantidad());
			System.out.println("Se agrego producto");
			root.put("msg", "success");
		}
		
		return new ModelAndView("jsonView", root);
		
    }
	
	
	public ModelAndView save(HttpServletRequest request, HttpServletResponse response)
    throws Exception {

		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Const.SESSION_KEY);
		
		JSONObject root = new JSONObject();
		
		if(user==null){
			root.put("msg", "login");	
		}else{
			
			UsuarioWeb usuario = new UsuarioWeb(user.getLogin());
			
			getForm(request);

			Carrito carrito = carritoDAO.existCarrito(usuario);
			System.out.println("exuste carrito? ");
			if(carrito!=null){
				
				Producto producto = carritoDAO.findProductoById(new Integer(form.getProductoId()));
				
				carritoDAO.actualizarProducto(producto, carrito, form.getCantidad());
				root.put("msg", "success");
				
			}else{
				System.out.println("no existe carrito");
			}
			
			
		}
		
		return new ModelAndView("jsonView", root);
		
    }
	
	
	public ModelAndView eliminar(HttpServletRequest request, HttpServletResponse response)
    throws Exception {

		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Const.SESSION_KEY);
		
		JSONObject root = new JSONObject();
		
		if(user==null){
			root.put("msg", "login");	
		}else{
			
			UsuarioWeb usuario = new UsuarioWeb(user.getLogin());
			
			getForm(request);

			Carrito carrito = carritoDAO.existCarrito(usuario);
			System.out.println("exuste carrito? ");
			if(carrito!=null){
				
				Producto producto = carritoDAO.findProductoById(new Integer(form.getProductoId()));
				
				carritoDAO.quitarProducto(producto, carrito);
				root.put("msg", "success");
				
			}else{
				System.out.println("no existe carrito");
			}
			
			
		}
		
		return carrito(request, response);
		
    }
	
	
	
	public ModelAndView eliminarTodo(HttpServletRequest request, HttpServletResponse response)
    throws Exception {

		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Const.SESSION_KEY);
		
		JSONObject root = new JSONObject();
		
		if(user==null){
			root.put("msg", "login");	
		}else{
			
			UsuarioWeb usuario = new UsuarioWeb(user.getLogin());
			
			getForm(request);

			Carrito carrito = carritoDAO.existCarrito(usuario);
			System.out.println("exuste carrito? ");
			if(carrito!=null){
				
				carritoDAO.quitarProductos(carrito);
				root.put("msg", "success");
				
			}else{
				System.out.println("no existe carrito");
			}
			
			
		}
		
		return carrito(request, response);
		
    }
	
	
	public ModelAndView pagar(HttpServletRequest request, HttpServletResponse response)
    throws Exception {

		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Const.SESSION_KEY);
		boolean success = false;
		if(user!=null){
			
			UsuarioWeb usuario = new UsuarioWeb(user.getLogin());
			
			getForm(request);

			Carrito carrito = carritoDAO.existCarrito(usuario);
			System.out.println("exuste carrito? ");
			if(carrito!=null){
				
				carritoDAO.grabarCarrito(carrito);
				success = true;
				
			}else{
				System.out.println("no existe carrito");
			}
			
			
		}
		
		ModelAndView m = carrito(request, response);
		if(success)
			m.addObject("compra", "Carrito grabado");
		return m;
		
    }

/** Repetir si es que utiliza FORM en otros controllers ***/
	
	public Object getCommandObject(HttpServletRequest request)
	throws Exception {
		Object command = formBackingObject(request);
		bind (request, command);
		return command;
	}
	
	protected Object formBackingObject(HttpServletRequest request)
	throws Exception {
		return commandClass.newInstance();
	}

	public Class<?> getCommandClass() {
		return commandClass;
	}

	public void setCommandClass(Class<?> commandClass) {
		this.commandClass = commandClass;
	}

	public CarritoComprasForm getForm(HttpServletRequest request) throws Exception {
		Object command = getCommandObject(request);
    	form = (CarritoComprasForm)command;
		return form;
	}
	
	
	
}
